package com.quanshu.change.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.quanshu.change.entity.BackGroundEntity;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.profile.DialogShare;
import com.quanshu.exchange.ui.gui.qrcode.utils.QrUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.quanshu.exchange.support.utils.Util.bmpToByteArray;

public class InviteResgisActivity extends BaseActivity {


    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.back_ground)
    ConstraintLayout backGround;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.img)
    CustomImgview img;

    private Bitmap mBitmap;
    private IWXAPI iwxapi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_resgis);
        ButterKnife.bind(this);
        iwxapi = WXAPIFactory.createWXAPI(this, MyApplication.getInstance().getWX_ID(), false);
        img.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mBitmap != null) {
                    new AlertDialog.Builder(InviteResgisActivity.this).setTitle("提示").setMessage("您确定要保存此图片到本地吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                saveImg(mBitmap, "牛兑换分享图片" + System.currentTimeMillis());
                            } catch (IOException e) {

                            }

                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).show();
                }
                return true;
            }
        });
        initListener();
        getBalanceHistoryInfo();
    }

    private void initListener() {
        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        RxViewHelper.getInstance().clicks(tvShare, aVoid -> {
            DialogShare dialogShare = new DialogShare(this);
            dialogShare.show();
            //分享到微信
            dialogShare.getWeChatSubject().subscribe(o -> {
                doShareWeChat("weChat");
                dialogShare.cancel();
            });
            //分享到朋友圈
            dialogShare.getFriendsSubject().subscribe(o -> {
                doShareWeChat("friends");
                dialogShare.cancel();
            });
        });
    }

    //获取二维码背景
    private void getBalanceHistoryInfo() {
        if (currentUser != null) {
            NetClient.getInstance().getShopService(ShopInterface.class)
                    .getActivityImg(AppUtils.getSignParams(currentUser.getUser_id() + ""), currentUser.getUser_id() + "")
                    .compose(new BaseTransformer<>(this, true, false))
                    .subscribe(new BaseObserver<BaseResponse<BackGroundEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<BackGroundEntity> response) {
                            try {
                                Glide.with(InviteResgisActivity.this).asBitmap().load(Config.URL_HOST_SHOP + response.getInfo().getImg_url()).into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                        int w = resource.getWidth();
                                        //int h=resource.getHeight();
                                        Canvas canvas = new Canvas(resource);
                                        String url = Config.URL_HOST_SHOP + "cattle_exchange_show/sRegister?" + currentUser.getMemberid();
                                        mBitmap = QrUtils.createImage(url, w / 3, w / 3, null);
                                        canvas.drawBitmap(mBitmap, 260, 840, null);
                                        mBitmap = resource;
                                        //backGround.setBackgroundColor(mBitmap.getPixel(mBitmap.getWidth()-1,mBitmap.getHeight()-1));
                                        img.setImageBitmap(resource);
                                    }
                                });
                            } catch (Exception e) {
                                Log.d("分享图片", "onSuccess: 生成失败");
                            }

                        }

                        @Override
                        public void onFailure(Throwable e) {
                            LogUtil.printException(e);
                        }
                    });
        }
    }


    private void doShareWeChat(String type) {
        if (mBitmap == null) {
            ToastHelper.toast("图片生成中");
            return;
        }
        WXImageObject wxImageObject = new WXImageObject(mBitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;
        //设置缩略图
        Bitmap mBp = Bitmap.createScaledBitmap(mBitmap, mBitmap.getWidth() / 10, mBitmap.getHeight() / 10, true);
        msg.thumbData = bmpToByteArray(mBp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");//  transaction字段用
        req.message = msg;
        if (type.equals("weChat")) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else if (type.equals("friends")) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        iwxapi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    protected void onDestroy() {
        if (mBitmap != null && mBitmap.isRecycled()) {
            mBitmap.recycle();
            mBitmap = null;
        }
        super.onDestroy();
    }


    private void saveImg(Bitmap bitmap, String bitName) throws IOException {
        File file = new File("/sdcard/DCIM/Camera/" + bitName + ".jpg");
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                out.flush();
                out.close();
                //保存图片后发送广播通知更新数据库
                // Uri uri = Uri.fromFile(file);
                // sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                this.sendBroadcast(intent);
                ToastHelper.toast("保存成功");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
